<template>
    <div class="course-list flex flex-col sm:flex-row dark:bg-regal-dark w-full">
        <div class="w-full ml-0 sm:ml-2 mt-2 sm:mt-0 mb-6">
            <div class="config-main pl-5 pb-5">
                <div class="pt-5 pl-2">
                    基础配置
                </div>
                <div class="mt-6">
                    <el-form :label-width="200">
                        <el-form-item label="用户最多可预约天数"  required>
                            <el-input-number v-model="configForm.max_rev_day" :min="1" :max="1000" label="天"></el-input-number>
                        </el-form-item>
                        <el-form-item label="用户在课程开始" required>
                            <el-input-number v-model="configForm.max_cancel_time" :min="1" :max="1000" label="天" class="mr-3.5"></el-input-number> 分钟前可取消预约
                        </el-form-item>
                        <el-form-item label="默认上课时间" required>
                            <div class="flex flex-wrap">
                                <template v-for="item in classTimeData">
                                    <el-input class="mr-4 mb-3" v-if="configForm.choose_time.indexOf(item.id) != -1" style="width: 120px" disabled :placeholder="item.name" ></el-input>
                                </template>
                                <el-button type="text" class="link" @click="editClassTime" >编辑</el-button>
                            </div>
                        </el-form-item>

                    </el-form>
                </div>
                <div class="footer">
                    <div class="flex  items-center">
                        <el-button type="primary" @click="saveConfig"><Icon name="plus" className="w-3 h-4 mr-1" /> 保存</el-button>
                        <el-button ><Icon name="plus" className="w-3 h-4 mr-1" /> 取消</el-button>
                    </div>
                </div>
            </div>
            <div class="config-main pl-5 pb-5 mt-6">
                <div class="pt-5 pl-2">
                    学科配置
                </div>
                <div class="mt-6">
                    <div class="pt-5 pl-2 flex">
                        <el-input class="mr-3" placeholder="请输入年纪名称" v-model="gradeName" style="width: 300px"></el-input>
                        <el-button type="primary" link @click="addGrade"><Icon name="plus" className="w-4 h-4 mr-1" /> 添加年级</el-button>
                    </div>
                </div>
                <el-table
                    :data="gradeSubjectData"
                    class="mt-3 mb-6"
                    style="width: 100%"
                >
                    <el-table-column
                        prop="name"
                        label="年级"
                    ></el-table-column>
                    <el-table-column
                        prop="subjectText"
                        label="学科"
                    ></el-table-column>
                    <el-table-column
                        prop="value3"
                        label="操作"
                    >
                        <template #default="scope">
                            <el-space :size="10" spacer="|">
                                    <el-button type="text" class="link" @click="editGrade(scope.row)">编辑</el-button>
                                    <el-button type="text" class="link" @click="deleteGrade(scope.row)">删除</el-button>
                            </el-space>

                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="config-main pl-5 pb-5 mt-6">
                <div class="pt-5 pl-2">
                    营销配置
                </div>
                <div class="mt-6">
                    <el-form :label-width="200" :rules="rules" ref="configFormRef">
                        <el-form-item label="首页banner图" required>
                            <el-upload
                                v-model:file-list="fileList"
                                action="http://192.168.1.8:9999/api/configuration/upload"
                                list-type="picture-card"
                                :on-preview="handlePictureCardPreview"
                                :on-remove="handleRemove"
                            >
                                <el-icon><Plus /></el-icon>
                            </el-upload>


                        </el-form-item>
                        <el-form-item label="关于我们描述" required>
                            <el-input class="w-1/2" v-model="configForm.about_us" type="textarea" placeholder="请输入"></el-input>
                        </el-form-item>

                    </el-form>
                </div>
                <div class="footer">
                    <div class="flex  items-center">
                        <el-button type="primary" @click="saveConfig"><Icon name="plus" className="w-3 h-4 mr-1" /> 保存</el-button>
                        <el-button ><Icon name="plus" className="w-3 h-4 mr-1" /> 取消</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <el-dialog v-model="classTimeDialogVisible" title="修改默认上课时间">
        <div class="edit-dialog">
            <el-form :label-width="100">
                <el-form-item label="默认上课时间">
                    <div>
                        <el-checkbox
                            v-model="checkAll"
                            :indeterminate="isIndeterminate"
                            @change="handleCheckAllChange"
                        >全选</el-checkbox
                        >
                        <el-checkbox-group
                            v-model="checkTimeData"
                            @change="handleCheckedCitiesChange"
                        >
                            <el-checkbox
                                v-for="item in classTimeData"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >{{ item.name }}</el-checkbox
                            >
                        </el-checkbox-group>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="classTimeDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="classTimeConfirm">
                    确定
                </el-button>
            </div>
        </template>

    </el-dialog>
    <el-dialog v-model="dialogVisible" title="预览图片">
        <img style="height:50vh;width: auto" :src="dialogImageUrl" alt />
    </el-dialog>
    <el-dialog v-model="editSubjectVisible" :title="`编辑学科-${editGradeObg.name}`">
        <div class="flex gap-2">
            <el-tag v-for="(item, index) in subjects" :key="item.id" closable :type="item.type" @close="deleteSubject(item , index)">
                {{ item.name }}
            </el-tag>
        </div>
        <div class="mt-6">
            <div class="pt-5 pl-2 flex">
                <el-input class="mr-3" placeholder="请输入学科名称" v-model="subjectName" style="width: 300px"></el-input>
                <el-button type="primary" link @click="addSubject"><Icon name="plus" className="w-4 h-4 mr-1" /> 添加学科</el-button>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editSubjectVisible = false">关闭</el-button>
            </div>
        </template>

    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, unref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import http from '/admin/support/http'
import { Code } from '/admin/enum/app'
import Message from '/admin/support/message'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessageBox } from 'element-plus'


const rules = ref({
    about_us: [
        { required: true, message: '请输入关于我们', trigger: 'blur' },
    ],
})

//基础配置板块
const configForm = ref({
    max_rev_day: 1, //用户最多可预约天数
    max_cancel_time: 1, //用户在课程开始多少分钟前可取消预约
    banners: [], //首页banner图
    about_us: '', //关于我们描述
    choose_time: [], //默认上课时间
})
const classTimeDialogVisible = ref(false)
const editClassTime = () => {
    classTimeDialogVisible.value = true
}

const checkAll = ref(false)
const isIndeterminate = ref(true)
const checkTimeData = ref([])
const classTimeData = ref([])
const loading = ref(false)
const configFormRef = ref(null)

const handleCheckAllChange = (val: boolean) => {
    checkTimeData.value = val ? classTimeData.value.map((item) => { return  item.id}) : []
    isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === classTimeData.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < classTimeData.value.length
}

const classTimeConfirm = () => {
    if (!checkTimeData.value.length) return Message.error('请选择默认上课时间')
    configForm.value.choose_time = checkTimeData.value
    classTimeDialogVisible.value = false

}

//获取基础配置
function getConfig() {
    loading.value = true
    http.get('/configuration/index')
        .then(r => {
            loading.value = false
            if (r.data.code === Code.SUCCESS) {
                let data = r.data.data
                configForm.value = data
                classTimeData.value = data?.all_time
                checkTimeData.value = data?.choose_time
                fileList.value  = data?.banners.map((item: string) => {
                    return {
                        url: item
                    }
                })
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
            loading.value = false
        })
}

//保存基础配置
function saveConfig() {

    const params = {
        about_us: configForm.value.about_us,
        max_cancel_time: configForm.value.max_cancel_time,
        banners: fileList.value.map((item) => { return item.response?.path || item.url }).join(','),
        max_rev_day: configForm.value.max_rev_day,
        choose_time: checkTimeData.value.join(',')
    }
    if (!params.about_us) return Message.error('请输入关于我们')
    if (!params.banners) return Message.error('请上传首页banner图')
    loading.value = true
    http.post('/configuration/update', unref(params))
        .then(r => {
            loading.value = false
            if (r.data.code === Code.SUCCESS) {
                Message.success('保存成功')
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
            loading.value = false
        })
}


getConfig()
getGradeSubject()




const fileList = ref<UploadUserFile[]>([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

const gradeName = ref('')
const subjects = ref([])
const editSubjectVisible = ref(false)
const gradeSubjectData = ref([])
const editGradeObg = ref({})
const subjectName = ref('')

//获取学科配置
function getGradeSubject() {
    loading.value = true
    http.get('/grade/list')
        .then(r => {
            loading.value = false
            if (r.data.code === Code.SUCCESS) {
                console.log(r.data.data, 'r.data.data')
                let data = r.data.data?.map((item: any) => {
                    return {
                        ...item,
                        subjectText: item.subject?.map((item: any) => {
                            return item.name
                        }).join(',') || '-'
                    }
                })
                gradeSubjectData.value = data
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
            loading.value = false
        })
}

//添加年级
function addGrade() {
    if (!gradeName.value) return Message.error('请输入年级名称')
    loading.value = true
    http.post('/grade/add', { name: gradeName.value })
        .then(r => {
            loading.value = false
            if (r.data.code === Code.SUCCESS) {
                Message.success('添加成功')
                gradeName.value = ''
                getGradeSubject()
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
            loading.value = false
        })
}

//编辑年级
function editGrade(scope: any) {
    editGradeObg.value = scope
    subjects.value = scope.subject
    editSubjectVisible.value = true
}

//添加学科
function addSubject() {
    if (!subjectName.value) return Message.error('请输入学科名称')
    //判断 subjectName 是否已经存在
    if (subjects.value && subjects.value.some((item: any) => item.name === subjectName.value)) return Message.error('学科名称已存在')

    loading.value = true
    http.post('/subject/add', { name: subjectName.value, grade_id: editGradeObg.value.id })
        .then(r => {
            loading.value = false
            if (r.data.code === Code.SUCCESS) {
                Message.success('添加成功')
                subjects.value.push({ name: subjectName.value, id: r.data.data })
                subjectName.value = ''
                getGradeSubject()
            } else {
                Message.error(r.data.message)
            }
        })
        .finally(() => {
            loading.value = false
        })

}

//删除学科
function deleteSubject(item: any, index: number) {
    loading.value = true
    //删除询问弹窗
    ElMessageBox.confirm(
        '确定删除该学科?',
        '警告',
        {
            type: 'warning',
        }
    )
        .then(() => {
            http.post('/subject/delete', { id: item.id })
                .then(r => {
                    loading.value = false
                    if (r.data.code === Code.SUCCESS) {
                        subjects.value.splice(index, 1)
                        Message.success('删除成功')
                        getGradeSubject()
                    } else {
                        Message.error(r.data.message)
                    }
                })
                .finally(() => {
                    loading.value = false
                })
        })
        .catch(() => {

        })

}

//删除年级
function deleteGrade(item: any) {
    loading.value = true
    //删除询问弹窗
    ElMessageBox.confirm(
        '确定删除该年级?',
        '警告',
        {
            type: 'warning',
        }
    )
        .then(() => {
            http.post('/grade/delete', { id: item.id })
                .then(r => {
                    loading.value = false
                    if (r.data.code === Code.SUCCESS) {
                        Message.success('删除成功')
                        getGradeSubject()
                    } else {
                        Message.error(r.data.message)
                    }
                })
                .finally(() => {
                    loading.value = false
                })
        })
        .catch(() => {

        })

}




</script>

<style scoped lang="scss">
.course-list {
    height: calc(100vh - 120px);
}
.table-default {
    height: calc(100% - 180px);
}
.config-main {
    background: #fff;
    border-radius: 8px;
}
.edit-dialog {
    padding: 36px;
}
</style>
